package io;

import java.io.*;
import java.util.Scanner;

public class IODemo16 {
    public static void main(String[] args) {
        System.out.println("请输入路径");
        Scanner sc = new Scanner(System.in);
        String rootPath = sc.next();
        System.out.println("输入查找的单词");
        String word = sc.next();
        File f = new File(rootPath);
        if(!f.isDirectory()){
            System.out.println("输入有误");
            return;
        }
        scanDir2(f,word);
    }

    private static void scanDir2(File f, String word) {
        File[] files = f.listFiles();
        if(files == null){
            return;
        }
        for(File file : files){
            if(file.isDirectory()){
                scanDir2(file,word);
            } else if(file.isFile()){
                findInFile(file,word);
            } else {
                ;
            }
        }
    }

    private static void findInFile(File file, String word) {
        try(InputStream inputStream = new FileInputStream(file)){
            StringBuilder sb = new StringBuilder();
            while(true){
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n == -1){
                    break;
                }
                String s = new String(buffer,0,n);
                sb.append(s);
            }
            if(sb.indexOf(word) ==  -1){
                return;
            }
            System.out.println("找到了" + file.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
